package utfpr.si.servants;
import java.awt.geom.Point2D;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

import utfpr.si.interfaces.IServidor;
import bean.Robo;

public class Servidor extends UnicastRemoteObject implements IServidor {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static HashMap<String, Robo> content = new HashMap<String,Robo>();
	public static HashMap<String, String> acoes = new HashMap<String,String>();
	private Robo refemEnemy = null;
	private final int MAX_DIST = 2121;
	private static final String robos[] = {
		"sample.RoboA (1)",
		"sample.RoboA (2)",
		"sample.RoboA (3)",
		"sample.RoboA (4)",
		"sample.RoboA (5)",
		"sample.RoboA (6)",
		"sample.RoboA (7)",
		"sample.RoboA (8)"
	}; 
    public Servidor()throws RemoteException{
    	content.clear();
    }
	@Override
	public void updateTable(String target, double x, double y) throws RemoteException {
		Robo r = content.get(target);
		if( r == null ) content.put(target, new Robo(target, x, y));
		else{
			r.setX(x);
			r.setY(y);
			content.put(target, r);
		}
	}
	@Override
	public String getAction(String ag) throws RemoteException {
		String retorno = acoes.get(ag);
		if( retorno == null || retorno.isEmpty() )
			retorno = "Aguardar";
		return retorno;
	}
	@Override
	public double[] getStatus() throws RemoteException {
		double[] input = new double[8];
		Robo refem = content.get("sample.RoboAR (1)");
		if(  refem != null && content.size() == 9 ){
			int i = 0;
			for(String robo : robos){
				Robo r = content.get(robo);
				if( r != null )
					input[i] = Point2D.distance(r.getX(), r.getY(),refem.getX(), refem.getY())/MAX_DIST;
				i++;
			}
		}else{
			input = null;
		}
		return input;
	}
	@Override
	public void setAction(String ag, String action) throws RemoteException {
		acoes.put(ag, action);
	}
	@Override
	public Robo getRefem() throws RemoteException {
		return content.get("sample.RoboAR (1)");
	}
	@Override
	public Robo getRefemEnemy() throws RemoteException {
		return refemEnemy;
	}
	@Override
	public void setRefemEnemy(String name, double x, double y)
			throws RemoteException {
		refemEnemy = new Robo(name, x, y);
	}
}